package com.shbaiche.bifenba.ui.base;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import butterknife.BindView;
import cn.droidlover.xdroid.base.XActivity;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.kit.AppKit;
import com.shbaiche.bifenba.model.base.Passport;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.video.ArticleDetailMessage;
import com.shbaiche.bifenba.model.video.ArticleShareMessage;
import com.shbaiche.bifenba.model.video.ArticleVo;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.my.LoginActivity;
import com.shbaiche.bifenba.ui.my.SettingsActivity;
import com.shbaiche.bifenba.ui.video.VideoDetailActivity;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;

import java.util.List;

import cn.droidlover.xdroidbase.router.Router;
import cn.droidlover.xstatecontroller.XStateController;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import okhttp3.Call;

/**
 * Created by wanglei on 2016/12/11.
 */

public class WebActivity extends XActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @BindView(R.id.contentLayout)
    XStateController contentLayout;
    @BindView(R.id.toolbar_tv_right)
    TextView ping;

    String url;
    String desc;
    int id;

    private Handler mHandler = new Handler();

    public static final String PARAM_URL = "url";
    public static final String PARAM_DESC = "desc";


    @Override
    public void initData(Bundle savedInstanceState) {
        url = getIntent().getStringExtra(PARAM_URL);
        desc = getIntent().getStringExtra(PARAM_DESC);


        if ("资讯详情".equals(desc)) {
            ping.setVisibility(View.VISIBLE);
            id = getIntent().getIntExtra("id", 0);


            ArticleDetailMessage msg = new ArticleDetailMessage();
            msg.setArticleId(Long.valueOf(id));

            NetApi.videoListDetail(msg, new JsonCallback<TransMessage>() {

                @Override
                public void onFail(Call call, Exception e, int id) {
                    contentLayout.showContent();
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    contentLayout.showContent();
                    ToastUtil.show("onFail" + e.getMessage());
                }

                @Override
                public void onResponse(TransMessage response, int id) {

                    contentLayout.showContent();

                    Gson gson = new Gson();
                    ArticleDetailMessage msg = gson.fromJson(response.getMessage(), ArticleDetailMessage.class);

                    if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {

                        ArticleVo vo = msg.getArticleVo();
                        if (vo != null && vo.getDiscussNum() != null) {
                            ping.setText(vo.getDiscussNum() + "评论");
                        }
                    } else {
                    }

                }
            });
        }
        initToolbar();
        initContentLayout();
        initRefreshLayout();
        initWebView();
    }


    @Override
    public void setListener() {

    }

    private void initContentLayout() {
        contentLayout.loadingView(View.inflate(context, R.layout.view_loading, null));
    }

    private void initRefreshLayout() {
        swipeRefreshLayout.setColorSchemeResources(
                android.R.color.holo_blue_light,
                android.R.color.holo_red_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_green_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.loadUrl(url);
            }
        });

    }

    private void initWebView() {
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    if (contentLayout != null)
                        contentLayout.showContent();
                    if (webView != null)
                        url = webView.getUrl();
                } else {
                    if (contentLayout != null)
                        contentLayout.showLoading();
                }
            }
        });
        webView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                if (swipeRefreshLayout != null)
                    swipeRefreshLayout.setRefreshing(false);
            }
        });
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.addJavascriptInterface(new AndroidForJavascriptInterface(), "goAndroid");
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.getSettings().setAppCacheEnabled(true);

        //http://188z20966o.iok.la:41428/article/detail.htm?articleId=23
        //http://localhost:8077/article/detail.htm?articleId=35&userName=15914173827&token=c860ffe41ab347b4c5ef23064e611339
        Passport p = App.getPassport();
        if (p != null) {
            if (!TextUtils.isEmpty(url) && url.indexOf("detail.htm") != -1) {
                url += "&userName=" + p.getUserName() + "&token=" + p.getToken();
            }
        }
        webView.loadUrl(url);
    }


    private void initToolbar() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_white_24dp);
        getSupportActionBar().setTitle(desc);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
            case R.id.action_share:
                AppKit.shareText(this, webView.getTitle() + " " + webView.getUrl() + " 来自「XDroid」");
                break;
            case R.id.action_refresh:
                webView.reload();
                break;
            case R.id.action_copy:
                AppKit.copyToClipBoard(this, webView.getUrl());
                break;
            case R.id.action_open_in_browser:
                AppKit.openInBrowser(this, webView.getUrl());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    finish();
                }
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) webView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) webView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (webView != null) {
            ViewGroup parent = (ViewGroup) webView.getParent();
            if (parent != null) {
                parent.removeView(webView);
            }
            webView.removeAllViews();
            webView.destroy();
        }
    }

    public static void launch(Activity activity, String url, String desc, int id) {
        Router.newIntent(activity)
                .to(WebActivity.class)
                .putString(PARAM_URL, url)
                .putString(PARAM_DESC, desc)
                .putInt("id", id)
                .launch();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    protected class AndroidForJavascriptInterface {
        @JavascriptInterface
        public void startLogin() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    if (App.getPassport() == null) {
                        LoginActivity.launch(context);
                        finish();
                    }
                }
            });
        }

        @JavascriptInterface
        public void articleShare() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    ArticleShareMessage msg = new ArticleShareMessage();
                    msg.setArticleId(Long.valueOf(id));
                    NetApi.ArticleShare(msg, new JsonCallback<TransMessage>() {

                        @Override
                        public void onFail(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onError(Call call, Exception e, int id) {
                            ToastUtil.show("onFail" + e.getMessage());
                        }

                        @Override
                        public void onResponse(TransMessage response, int id) {
                            Gson gson = new Gson();
                            ArticleShareMessage msg = gson.fromJson(response.getMessage(), ArticleShareMessage.class);

                            if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                                AppKit.shareText(WebActivity.this, msg.getTitle() + msg.getUrl());
                            } else {
                            }
                        }
                    });
                }
            });
        }
    }

}
